import * as queryString from "node:querystring"
import * as fs from "fs"
import * as request from "request"

const HttpOptions = {
    url: `http://rinkeby.infura.io/v3`,
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    // body: `{"jsonrpc":"2.0","method":"eth_getBlockByNumber","params":["latest",true], "id":1}`
}

class HttpTools {
    /**
     * 
     * @param {HttpOptions} options 
     * @param {string} data 
     */
    async post(options:any, data:any) {
        // var headers = {
        //     'Content-Type': 'application/json'
        // };

        // var dataString = '{"jsonrpc":"2.0","method":"eth_getBlockByNumber","params":["latest",true], "id":1}';

        // var options = {
        //     url: `https://rinkeby.infura.io/v3/${process.env.PROJECT_ID}`,
        //     method: 'POST',
        //     headers: headers,
        //     body: dataString,
        // };

        if(data){
            if (typeof (data) === "string") {
                options.body = data;
            } else {
                options.body = JSON.stringify(data);
            }    
        }

        
            return new Promise((resolve, reject) => {
                function callback(error:any, response:any, body:any) {
                    if (!error && response.statusCode == 200) {
                        let json = response.body;
                        let obj = JSON.parse(json);
                        console.log(obj);
                        resolve(obj)
                    } else {
                        reject({ error, response })
                    }
                }
    
                request(options, callback);
            }).catch((e)=>{
                console.warn(e)
            })

    }
    async download(url:string, filename:string) {
        return new Promise((resolve, reject) => {
            request({ uri: url, encoding: 'binary' }, function (err, res) {

                if (err) {
                    console.error(err);
                    reject(err);
                } else {

                    fs.writeFile(filename, res.body, "binary", function (err) {

                        if (err) {

                            console.log("保存失败");
                        }

                        console.log("保存成功");

                    });
                    resolve(filename);
                }
            })
        })
    }
    async get(options:any, data:any) {
        if (typeof (options) != "string") {
            options.uri += "?" + queryString.encode(data);
        } else {
            options += "?" + queryString.encode(data);
        }

        return new Promise((resolve, reject) => {
            request(options, function (error:any, response:any, body:any) {
                if (!error && response.statusCode == 200) {
                    console.log(body) // 请求成功的处理逻辑
                    resolve(body)
                } else {
                    reject({ error, response, body });
                }
            })

        })

    }
}

const httpTools = new HttpTools();
module.exports = httpTools;